﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ChairtyBank.DAL;

namespace ChairtyBank
{
    public partial class InstalmentForm : Form
    {
        public InstalmentForm()
        {
            InitializeComponent();
        }
        private const String LAW_BRANCH = "لجنة قانونية";
        public Int32 user = -1;
        private Int32 clientID = 0;
        private Int32 ProjectId = 0;
        private Int32 loanId = 0;


        private ClientEntity clientEntity;
        private ProjectEntity projectEntity;
        private LoanEntity loanEntity;

        private void InstalmentForm_Load(object sender, EventArgs e)
        {
        }

        private void nameTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                List<ClientEntity> c = Client.GetClients("%" + nameTxt.Text + "%");
                if (c.Count == 0)
                    MessageBox.Show("هذا العميل غير موجود");
                else if (c.Count == 1)
                    publishClientValues(c[0]);
                else
                    showGridView(c);
            }
          }


        public void publishClientValues(ClientEntity ce)
        {
            clearAllData();
            clientEntity = ce;
            clientID = ce.Id;
            this.nameTxtt.Text = ce.Name;
            this.phoneTxt.Text = ce.Phone;
            this.addressTxt.Text = ce.Address;
            this.idTxtt.Text = ce.Id.ToString();
            this.jobTxt.Text = ce.Job;
            //this.DOBpicr.Value = ce.DateOfBirth;
            this.akhsTxt.Text = ce.Akhesaye;
            this.txtCycle.Text = ce.Round.ToString();
            this.nameTxtt.SelectAll();
            this.nameTxtt.Copy();

            getLoanAndProjectDetails(clientID);

            NotesEntity entity = CNotes.GetNote(clientID);
            if (entity != null)
            {
                MessageBox.Show(entity.C_Note);
                txtCNotes.Text = entity.C_Note;
            }
        }

        private void publishProjectValues(ProjectEntity pe)
        {
            ProjectId = pe.Id;
            placeTxt.Text = pe.Place;
            titleTxt.Text = pe.Title;

            txtProjEstablish.Text = pe.Establish;
            txtProjType.Text = pe.Type;
        }

        private void publishLoanValues(LoanEntity l)
        {
            loanId = l.Id;
            txtperiod.Text = l.Period.ToString();
            txtInstalmentAmount.Text = l.Instalment_amount.ToString();
            txtEvery.Text = l.Instalment_every;
            txtLoanValue.Text = l.Value.ToString();
            endDatepkr.Value = l.EndDate;
            startDatepkr.Value = l.PayDate;
            txtRest.Text = l.Rest.ToString();
            txtPenalties.Text = l.Penalties.ToString();

        }

        private void publishLaonValues()
        {
            List<InstalmentEntity> ll = Instalment.GetInstalment(loanId);
            InstalmentDataGrid.DataSource = ll;
            InstalmentDataGrid.Visible = true;
            InstalmentGrp.Visible = true;
            

        }

        private void showGridView(List<ClientEntity> lc)
        {
            CustomerSearchForm dialogue = new CustomerSearchForm();
            dialogue.customerDataGrid.DataSource = lc;
            dialogue.currentForm = 1;
            dialogue.ShowDialog(this);
        }

        private void getLoanAndProjectDetails(Int32 clientID)
        {
            try
            {
                LoanEntity le = Loan.GetLoan(clientID);
                if (!le.Equals(null))
                {
                    loanEntity = le;
                    publishLoanValues(le);
                    ProjectEntity pe = Project.GetProject(le.Project_ID);
                    projectEntity = pe;
                    publishProjectValues(pe);
                    custDataGrp.Visible = true;
                    publishLaonValues();
                }
            }
            catch
            {
                MessageBox.Show("ادخل البيانات بشكل صحيح ");
            }



        }

        private void clearAllData()
        {
            clientID = 0;
            ProjectId = 0;
            loanId = 0;

            projectEntity = null;
            clientEntity = null;
            loanEntity = null;

            this.nameTxtt.Text = "";
            this.phoneTxt.Text = "";
            this.addressTxt.Text = "";
            this.idTxtt.Text = "";
            this.jobTxt.Text = "";
            this.placeTxt.Text = "";
            this.titleTxt.Text = "";
            this.txtEvery.Text = "";
            this.txtInstalmentAmount.Text = "";
            this.txtLoanValue.Text = "";
            this.txtperiod.Text = "";
            this.txtPenalties.Text = "";
            this.txtRest.Text = "";
            this.txtProjEstablish.Text = "";
            this.txtProjType.Text = "";
            this.akhsTxt.Text = "";
            this.txtCycle.Text = "";
            this.txtCNotes.Text = "";

        }

        private void InstalmentDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && Boolean.Parse(InstalmentDataGrid.Rows[InstalmentDataGrid.CurrentCellAddress.Y].Cells["Payed"].Value.ToString()) != true)
            {
                string InstalmentId = InstalmentDataGrid.Rows[InstalmentDataGrid.CurrentCellAddress.Y].Cells["IdColumn"].Value.ToString();

                AddInstalmentForm form = new AddInstalmentForm(Int32.Parse(InstalmentId), Int32.Parse(txtRest.Text), this.user);
                form.Owner = this;
                form.Visible = true;

            }
            else if(e.RowIndex != -1)
            {
                //TODO show the ticket for this person.
                string InstalmentId = InstalmentDataGrid.Rows[InstalmentDataGrid.CurrentCellAddress.Y].Cells["IdColumn"].Value.ToString();

                AddInstalmentForm form = new AddInstalmentForm(Int32.Parse(InstalmentId), Int32.Parse(txtRest.Text),this.user,true);
                form.Owner = this;
                form.Visible = true;
            }
        }

        private void idTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && idTxt.Text != "")
            {
                ClientEntity c = Client.GetClient(Int32.Parse(idTxt.Text));
                if (c == null || c.Equals(null))
                    MessageBox.Show("هذا العميل غير موجود");
                else
                    publishClientValues(c);

            }

        }

        private void refresh_Click(object sender, EventArgs e)
        {
            refreshForm();
        }

        public void refreshForm()
        {
            ClientEntity c = Client.GetClient(Int32.Parse(idTxtt.Text));
            if (c == null || c.Equals(null))
                MessageBox.Show("هذا العميل غير موجود");
            else
                publishClientValues(c);

        }
        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void idTxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (clientID != 0)
            {
                NotesEntity entity = new NotesEntity();
                entity.C_Id = clientID;
                entity.C_Note = txtCNotes.Text;
                bool flag = true;
                if (CNotes.GetNote(clientID) == null)
                    flag &= CNotes.Add(entity);
                else
                    flag &= CNotes.Update(entity);

                if (flag)
                {
                    if (txtCNotes.Text == LAW_BRANCH)
                    {
                        List<InstalmentEntity> insts = (List<InstalmentEntity>)InstalmentDataGrid.DataSource;
                        foreach (InstalmentEntity inst in insts)
                        {
                            if (!inst.payed)
                            {
                                inst.Notes = LAW_BRANCH;
                                Instalment.UpdateInstNote(inst);
                            }
                        }
                    }
                    MessageBox.Show("تم حفظ الملاحظة بنجاح");
                }
                else
                    MessageBox.Show("حدث خطأ أثناء الحفظ");
            }
            else
            {
                MessageBox.Show("يجب إختيار عميل أولا");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (clientID != 0)
            {
                if (CNotes.Delete(clientID))
                {
                    if (txtCNotes.Text == LAW_BRANCH)
                    {
                        List<InstalmentEntity> insts = (List<InstalmentEntity>)InstalmentDataGrid.DataSource;
                        foreach (InstalmentEntity inst in insts)
                        {
                            if (!inst.payed)
                            {
                                inst.Notes = "";
                                Instalment.UpdateInstNote(inst);
                            }
                        }
                    }
                    MessageBox.Show("تم الحذف بنجاح");
                    this.txtCNotes.Text = "";
                }
            }
            else
                MessageBox.Show("يجب إختيار عميل أولا");
        }

        private void txtCNotes_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            txtCNotes.Text = LAW_BRANCH;
        }

        private void InstalmentDataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }




    }
}
